﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Reflection;
using System.IO;
using System.Diagnostics;

namespace template_dll
{
    public partial class ChildForm : Form
    {
        public ChildForm()
        {
            InitializeComponent();
        }

        private const string namechcol = "Флаг";
        private SqlConnection conn;
        private DataTable dt_rep;
        private delegate void Deleg();
        private Deleg del;
        private Guid guid;
        private struct date_str { public DateTime dt; public string dtname; }
        private date_str[] dt_str = new date_str[] { };
        private string month;
        
        public static bool DisplayForm(System.Windows.Forms.Form theMDIParent)
        {
            ChildForm f = new ChildForm();
            f.MdiParent = theMDIParent;
            f.WindowState = FormWindowState.Maximized;
            f.Show();
            return true;
        }

        private string GetServ(string filename)
        {
            string str = "";
            using (StreamReader streamReader = new StreamReader(filename))
            {
                while (!streamReader.EndOfStream)
                {
                    str += streamReader.ReadLine();
                }
            }
            return str;
        }

        private void ChildForm_Load(object sender, EventArgs e)
        {
            conn = new SqlConnection(@"Server=" + GetServ("serv.txt") + ";Database=PharmOLAPDW;Integrated Security=True");
            dt_rep = new DataTable();

            SqlCommand getdate = conn.CreateCommand();
            getdate.CommandText = @"pas_MonthSel";
            getdate.CommandType = CommandType.StoredProcedure;
            DataTable date = new DataTable();
            if (conn.State == ConnectionState.Closed) conn.Open();
            date.Load(getdate.ExecuteReader());
            if (date.Rows.Count > 0)
            {
                foreach (DataRow dr in date.Rows)
                {
                    Array.Resize(ref dt_str, dt_str.Length + 1);
                    dt_str[dt_str.Length - 1].dt = Convert.ToDateTime(dr[0]);
                    dt_str[dt_str.Length - 1].dtname = dr[1].ToString();
                    comboBox1.Items.Add(dr[1].ToString());
                    if (DateTime.Now.Date.Month == Convert.ToDateTime(dr[0]).Month)
                        comboBox1.SelectedIndex = comboBox1.Items.Count - 1;
                }

            }
        }

        private void StartCreateRep(object sender, EventArgs e)
        {
            dataGridView1.DataSource = null;
            dt_rep.Clear();
            month = comboBox1.Text;
            del = new Deleg(CreateRep);
            this.Text += " Формируется";
            IAsyncResult asyncRes = del.BeginInvoke(new AsyncCallback(CallBackFunc), null); //
            panel1.Enabled = false;
            dataGridView1.Enabled = false;
        }

        private void CallBackFunc(IAsyncResult aRes)
        {
            del.EndInvoke(aRes);
            panel1.Invoke((Func<bool>)(() => panel1.Enabled = true));
            dataGridView1.Invoke((Func<bool>)(() => dataGridView1.Enabled = true));
            this.Invoke((Func<string>)(() => this.Text = this.Text.Replace(" Формируется", "")));
            dataGridView1.Invoke((Func<object>)(() => dataGridView1.DataSource = dt_rep.DefaultView));
        }

        private void CreateRep()
        {
            if (conn.State == ConnectionState.Closed) conn.Open();
            try
            {
                if (conn.State == ConnectionState.Closed) conn.Open();
                dt_rep.Load(RepProc(conn));      
                conn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                conn.Close();
            }

        }

        private SqlDataReader RepProc(SqlConnection sqlcon)
        {
            SqlCommand sqlcom = sqlcon.CreateCommand();
            sqlcom.CommandType = CommandType.StoredProcedure;
            sqlcom.CommandText = @"pas_DAC_Turnover";
            sqlcom.CommandTimeout = 300;

            sqlcom.Parameters.Add("@month", SqlDbType.Date);
            for (int i = 0; i < dt_str.Length; i++)
                if (dt_str[i].dtname == month) sqlcom.Parameters["@month"].Value = dt_str[i].dt;
            sqlcom.Parameters.Add("@arch", SqlDbType.Bit);
            sqlcom.Parameters["@arch"].Value = checkBox1.Checked;
            sqlcom.Parameters.Add("@dep", SqlDbType.Bit);
            sqlcom.Parameters["@dep"].Value = checkBox2.Checked;

            return sqlcom.ExecuteReader();
        }

        private void ExpToExcel(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.FileName = "Оборачиваемость - отделения";
            sfd.Filter = "Файл CSV | *.csv";
            if (sfd.ShowDialog() == DialogResult.OK)
            {   
                SaveDGVToCSVfile(sfd.FileName.ToString(), dataGridView1, true);
            }
        }

        public static bool SaveDGVToCSVfile(string filename, DataGridView table, bool openInExcel)
        {
            try
            {
                StreamWriter sw = new StreamWriter(filename, false, Encoding.Unicode);

                List<int> col_n = new List<int>();
                foreach (DataGridViewColumn col in table.Columns)
                    if (col.Visible)
                    {
                        sw.Write(col.HeaderText + "\t");
                        col_n.Add(col.Index);
                    }
                sw.WriteLine();
                int x = table.RowCount;
                if (table.AllowUserToAddRows) x--;

                for (int i = 0; i < x; i++)
                {
                    for (int y = 0; y < col_n.Count; y++)
                        sw.Write(table[col_n[y], i].Value + "\t");
                    sw.Write(" \r\n");
                }
                sw.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return false;
            }

            if (openInExcel)
            {
                try
                {
                    Process newProc = Process.Start("excel.exe", "\"" + filename + "\"");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
            }
            return true;
        }
    }
}
